"use client"

import { useState } from "react"
import { Button } from "@/components/ui/button"
import { Plus } from "lucide-react"
import { Lock } from "@/types/admin"
import { columns } from "./columns"
import { DataTable } from "@/components/common/data-table"
import { LockDialog } from "@/components/admin/lock-dialog"
import { DeleteDialog } from "@/components/admin/delete-dialog"
import { useAdminStore } from "@/lib/store"

export default function LocksPage() {
  const { locks, deleteLock } = useAdminStore()
  
  const [openAddEditDialog, setOpenAddEditDialog] = useState(false)
  const [openDeleteDialog, setOpenDeleteDialog] = useState(false)
  const [selectedLock, setSelectedLock] = useState<Lock | undefined>(undefined)

  const handleAddLock = () => {
    setSelectedLock(undefined)
    setOpenAddEditDialog(true)
  }

  const handleEditLock = (lock: Lock) => {
    setSelectedLock(lock)
    setOpenAddEditDialog(true)
  }

  const handleDeleteClick = (lock: Lock) => {
    setSelectedLock(lock)
    setOpenDeleteDialog(true)
  }

  const handleConfirmDelete = () => {
    if (selectedLock) {
      deleteLock(selectedLock.id)
      setOpenDeleteDialog(false)
    }
  }
  
  return (
    <div className="space-y-8">
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-2xl font-bold tracking-tight">锁具管理</h2>
          <p className="text-muted-foreground">
            管理系统中的所有锁具。
          </p>
        </div>
        <div className="flex items-center space-x-2">
          <Button onClick={handleAddLock}>
            <Plus className="mr-2 h-4 w-4" /> 新增锁具
          </Button>
        </div>
      </div>
      <DataTable 
        columns={columns({ 
          onEdit: handleEditLock, 
          onDelete: handleDeleteClick 
        })} 
        data={locks}
        searchPlaceholder="搜索锁具(支持名称、部门、钥匙ID等)"
      />

      <LockDialog
        open={openAddEditDialog}
        onOpenChange={setOpenAddEditDialog}
        lock={selectedLock}
      />

      <DeleteDialog
        open={openDeleteDialog}
        onOpenChange={setOpenDeleteDialog}
        onConfirm={handleConfirmDelete}
        title="删除锁具"
        description={`确定要删除锁具 "${selectedLock?.name}" 吗？此操作不可撤销。`}
      />
    </div>
  )
} 